package viper.ji;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.*;
import javax.media.control.*;
import javax.media.protocol.*;
import javax.media.format.*;

import java.io.IOException;
import java.io.File;
import java.util.Vector;

public class MediaTransmitter {

	public MediaLocator mediaLocator = null;
	public DataSink dataSink = null;
	public Processor mediaProcessor = null;
	
	private static final Format[] FORMATS = new Format[]{
		new AudioFormat(AudioFormat.ULAW_RTP)
		};
	private static final ContentDescriptor CONTENT_DESCRIPTOR =
		new ContentDescriptor(ContentDescriptor.RAW_RTP);

	public MediaTransmitter(MediaLocator locator) {
		mediaLocator = locator;
	}

	public void startTransmitting() throws IOException {
		mediaProcessor.start();
		dataSink.open();
		dataSink.start();
	}

	public void stopTransmitting(){
		try {
			dataSink.stop();
			dataSink.close();
			mediaProcessor.stop();
			mediaProcessor.close();
			System.out.println("stopped...");
		} catch (IOException ex) {
			Logger.getLogger(MediaTransmitter.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
	public void setDataSource(DataSource ds) throws IOException,
	NoProcessorException, CannotRealizeException, NoDataSinkException {


		mediaProcessor = Manager.createRealizedProcessor(
				new ProcessorModel(ds, FORMATS, CONTENT_DESCRIPTOR));


		dataSink = Manager.createDataSink(mediaProcessor.getDataOutput(),
				mediaLocator);
	}
	
	public static void main(String [] args) {
		
		DataSource source = null;

		try {
			
			MediaLocator locator = new MediaLocator("rtp://"+args[0]+"/audio");
			MediaTransmitter transmitter = new MediaTransmitter(locator);
			System.out.println("-> Created media locator: '" +
					locator + "'");
			
			AudioFormat format= new AudioFormat(AudioFormat.LINEAR, 
					44100, 
					16, 
					2); 

			Vector devices= CaptureDeviceManager.getDeviceList( format);
			CaptureDeviceInfo cdi = (CaptureDeviceInfo) devices.elementAt(0);
			
			source = Manager.createDataSource(
					cdi.getLocator());

			transmitter.setDataSource(source);
			System.out.println("-> Set the data source on the transmitter");

			transmitter.startTransmitting();
			System.out.println("-> Transmitting...");

		} catch (Throwable t) {
			t.printStackTrace();
		}
	}
}